'use strict';

const Controller = require('egg').Controller;

class OutfitController extends Controller {
  // 获取搭配列表
  async index() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    
    const query = ctx.query;
    const options = {
      page: parseInt(query.page) || 1,
      pageSize: parseInt(query.pageSize) || 20,
      style: query.style,
      season: query.season,
      occasion: query.occasion,
      is_favorite: query.is_favorite,
      keyword: query.keyword,
      sortBy: query.sortBy,
      sortOrder: query.sortOrder,
      minRating: query.minRating ? parseFloat(query.minRating) : undefined,
      minWearCount: query.minWearCount ? parseInt(query.minWearCount) : undefined,
      maxWearCount: query.maxWearCount ? parseInt(query.maxWearCount) : undefined,
    };

    try {
      const result = await service.outfit.getList(userId, options);
      
      ctx.body = {
        code: 200,
        message: '获取成功',
        data: result,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取搭配详情
  async show() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const outfitId = ctx.params.id;

    try {
      const outfit = await service.outfit.findById(outfitId, userId);
      if (!outfit) {
        ctx.throw(404, '搭配不存在');
      }

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: outfit,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 创建搭配
  async create() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;

    // 参数验证
    ctx.validate({
      name: { type: 'string', required: true, max: 100 },
      description: { type: 'string', required: false },
      style: { type: 'enum', values: ['casual', 'formal', 'business', 'sport', 'party', 'vintage', 'street'], required: false },
      season: { type: 'enum', values: ['spring', 'summer', 'autumn', 'winter', 'all'], required: false },
      clothing_ids: { type: 'array', required: true, itemType: 'int' },
    });

    try {
      const outfitData = {
        ...ctx.request.body,
        user_id: userId,
      };

      const outfit = await service.outfit.create(outfitData);

      ctx.body = {
        code: 200,
        message: '创建成功',
        data: outfit,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 更新搭配
  async update() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const outfitId = ctx.params.id;

    try {
      // 检查搭配是否存在且属于当前用户
      const outfit = await service.outfit.findById(outfitId, userId);
      if (!outfit) {
        ctx.throw(404, '搭配不存在');
      }

      const updateData = ctx.request.body;
      await service.outfit.updateById(outfitId, updateData);

      ctx.body = {
        code: 200,
        message: '更新成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 删除搭配
  async destroy() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const outfitId = ctx.params.id;

    try {
      // 检查搭配是否存在且属于当前用户
      const outfit = await service.outfit.findById(outfitId, userId);
      if (!outfit) {
        ctx.throw(404, '搭配不存在');
      }

      await service.outfit.deleteById(outfitId);

      ctx.body = {
        code: 200,
        message: '删除成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 添加衣服到搭配
  async addClothing() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const outfitId = ctx.params.id;

    ctx.validate({
      clothing_id: { type: 'int', required: true },
      position: { type: 'string', required: false },
      layer_order: { type: 'int', required: false },
      is_main: { type: 'boolean', required: false },
    });

    try {
      const outfit = await service.outfit.findById(outfitId, userId);
      if (!outfit) {
        ctx.throw(404, '搭配不存在');
      }

      const { clothing_id, position, layer_order, is_main } = ctx.request.body;
      
      // 检查衣服是否属于当前用户
      const clothing = await service.clothing.findById(clothing_id, userId);
      if (!clothing) {
        ctx.throw(404, '衣服不存在');
      }

      await service.outfit.addClothing(outfitId, clothing_id, { position, layer_order, is_main });

      ctx.body = {
        code: 200,
        message: '添加成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 从搭配中移除衣服
  async removeClothing() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const outfitId = ctx.params.id;
    const clothingId = ctx.params.clothing_id;

    try {
      const outfit = await service.outfit.findById(outfitId, userId);
      if (!outfit) {
        ctx.throw(404, '搭配不存在');
      }

      await service.outfit.removeClothing(outfitId, clothingId);

      ctx.body = {
        code: 200,
        message: '移除成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 收藏/取消收藏搭配
  async toggleFavorite() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const outfitId = ctx.params.id;

    try {
      const outfit = await service.outfit.findById(outfitId, userId);
      if (!outfit) {
        ctx.throw(404, '搭配不存在');
      }

      const isFavorite = !outfit.is_favorite;
      await service.outfit.updateById(outfitId, {
        is_favorite: isFavorite,
      });

      ctx.body = {
        code: 200,
        message: isFavorite ? '收藏成功' : '取消收藏成功',
        data: {
          is_favorite: isFavorite,
        },
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 搭配评分
  async rate() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const outfitId = ctx.params.id;

    ctx.validate({
      rating: { type: 'number', required: true, min: 1, max: 5 },
    });

    try {
      const outfit = await service.outfit.findById(outfitId, userId);
      if (!outfit) {
        ctx.throw(404, '搭配不存在');
      }

      const { rating } = ctx.request.body;
      await service.outfit.updateById(outfitId, { rating });

      ctx.body = {
        code: 200,
        message: '评分成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 复制搭配
  async copy() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const outfitId = ctx.params.id;

    try {
      const outfit = await service.outfit.findById(outfitId, userId);
      if (!outfit) {
        ctx.throw(404, '搭配不存在');
      }

      const newOutfit = await service.outfit.copy(outfitId, userId);

      ctx.body = {
        code: 200,
        message: '复制成功',
        data: newOutfit,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 今天穿这套
  async wearToday() {
    const { ctx } = this;
    const userId = ctx.state.user?.id || 1;
    const outfitId = ctx.params.id;

    try {
      // 检查搭配是否存在且属于当前用户
      const outfit = await ctx.model.Outfit.findOne({
        where: { id: outfitId, user_id: userId }
      });

      if (!outfit) {
        ctx.throw(404, '搭配不存在');
      }

      const today = new Date().toISOString().split('T')[0];

      // 检查今天是否已经有穿搭记录
      const existingTodayRecord = await ctx.model.WearRecord.findOne({
        where: {
          user_id: userId,
          wear_date: today
        }
      });

      let message = '已记录今日穿搭';
      let replacedOutfitId = null;

      if (existingTodayRecord) {
        // 如果今天已经穿了同一套搭配
        if (existingTodayRecord.outfit_id === outfitId) {
          ctx.body = {
            code: 200,
            message: '今天已经选择了这套搭配',
            data: { alreadySelected: true }
          };
          return;
        }

        // 如果今天穿了不同的搭配，则替换
        replacedOutfitId = existingTodayRecord.outfit_id;

        // 更新现有记录
        await ctx.model.WearRecord.update({
          outfit_id: outfitId
        }, {
          where: {
            user_id: userId,
            wear_date: today
          }
        });

        message = '已更换今日穿搭';
      } else {
        // 创建新的穿着记录
        await ctx.model.WearRecord.create({
          user_id: userId,
          outfit_id: outfitId,
          wear_date: today
        });
      }

      // 重新计算新搭配的统计
      const newWearCount = await ctx.model.WearRecord.count({
        where: { outfit_id: outfitId }
      });

      await ctx.model.Outfit.update({
        wear_count: newWearCount,
        last_worn_date: today
      }, {
        where: { id: outfitId }
      });

      // 如果有被替换的搭配，重新计算其统计
      if (replacedOutfitId) {
        const replacedWearCount = await ctx.model.WearRecord.count({
          where: { outfit_id: replacedOutfitId }
        });

        // 获取最后穿着日期
        const lastWearRecord = await ctx.model.WearRecord.findOne({
          where: { outfit_id: replacedOutfitId },
          order: [['wear_date', 'DESC']]
        });

        await ctx.model.Outfit.update({
          wear_count: replacedWearCount,
          last_worn_date: lastWearRecord ? lastWearRecord.wear_date : null
        }, {
          where: { id: replacedOutfitId }
        });
      }

      ctx.body = {
        code: 200,
        message,
        data: {
          newWearCount,
          replaced: !!replacedOutfitId,
          replacedOutfitId
        }
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }
}

module.exports = OutfitController;
